import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * @author jagoLyu
 * @Description:
 * @data 2019/10/10 22:11
 */
public class ExportWortUtil {
    private static Template template=null;

    private static void addTemplate() throws IOException {
        //创建配置实例
        Configuration configuration = new Configuration();

        //设置编码
        configuration.setDefaultEncoding("UTF-8");

        //ftl模板文件统一放至 com.lun.template 包下面
        configuration.setClassForTemplateLoading(ExportWortUtil.class, "/temp");
        //获取模板
        template = configuration.getTemplate("inword.ftl","utf-8");
    }
    public static void createWord(Map dataMap, String tempPath, String fileName){
        try {
            if(template==null){
                addTemplate();
            }
            //输出文件
            File outFile = new File(tempPath+File.separator+fileName);

            //如果输出目标文件夹不存在，则创建
            if (!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdirs();
            }

            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));


            //生成文件
            template.process(dataMap, out);

            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //预览
    public static void getHtmlWord(HttpServletResponse response,Map dataMap){
        try {
            if(template==null){
                addTemplate();
            }
            response.setContentType("text/html;charset=utf-8");
            template.process(dataMap,response.getWriter());
        }catch (Exception e){

        }
    }
    //下载
    public static void downloadWord(HttpServletResponse response,Map dataMap,String fileName){
        try {
            if(template==null){
                addTemplate();
            }
            response.setHeader("content-Type", "application/msword");
            // 下载文件的默认名称
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            template.process(dataMap,new OutputStreamWriter(response.getOutputStream(),"UTF-8"));
        }catch (Exception e){

        }
    }
}